<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <title></title>
    <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
    <link href="../css/mui.css" rel="stylesheet" />
    <link rel="stylesheet" href="../css/header.css">
    <style type="text/css">
        #my-meun {
            width: 100%;
            height: 44px;
            background: #007AFF;
            text-align: center;
            line-height: 44px;
        }
        
        #my-meun>p {
            font-size: 18px;
            color: white;
            font-weight: 800;
        }
        
        #link_mui_action {
            width: 50px;
            height: 50px;
            border-radius: 30%;
        }
        
        #my-meun-content {
            width: 100%;
        }
        
        .mui-off-canvas-wrap:not(.mui-slide-in).mui-scalable {
            background-image: url(../images/bg.png);
            background-size: cover;
        }
        
        #my-meun-content-one {
            text-align: center;
            padding: 25px;
            width: 100%;
            height: 700px;
            background-color: rgba(255, 255, 255, 0.55);
            box-shadow: rgba(255, 255, 255, 0.4) 0 4px 10px;
            backdrop-filter: blur(5px);
        }
        
        #my-meun-content-one>p {
            font-size: 18px;
            color: rgba(0, 0, 0, .7);
            font-weight: 800;
        }
        
        #my-meun-content-one>img {
            width: 200px;
            height: 230px;
            box-shadow: rgba(0, 0, 0, .4) 0 0 20px 10px;
            margin-top: 30%;
            margin-bottom: 20px;
        }
        
        #isRead {
            width: 10px;
            height: 10px;
            position: absolute;
            top: 10px;
            left: 50px;
            background-color: red;
            border-radius: 100%;
        }
    </style>

</head>


<body>
    <!-- 侧滑导航根容器 -->
    <div class="mui-off-canvas-wrap mui-draggable mui-scalable" id="main-bg">
        <!-- 菜单容器 -->
        <aside class="mui-off-canvas-left">
            <div class="mui-scroll-wrapper">
                <div class="mui-scroll">
                    <!-- 菜单具体展示内容 -->
                    <div class="mui-content" id="my-meun">
                        <p>个人信息</p>
                    </div>
                    <div class="mui-content" id="my-meun-content">
                        <div id="my-meun-content-one">
                            <img id="faceImage">
                            <p id="nickname"></p>
                            <p id="username"></p>
                        </div>
                    </div>
                </div>
            </div>
        </aside>
        <!-- 主页面容器 -->
        <div class="mui-inner-wrap">
            <!-- 主页面标题 -->
            <header class="mui-bar mui-bar-nav">
                <img style="height: 35px;width: 35px;margin-top: 4px;" id="link_mui_action" class="mui-pull-left"></img>
                <h1 id="wh-count" class="mui-title">微涵</h1>
            </header>
            <div class="mui-content mui-scroll-wrapper">
                <div class="mui-scroll">
                    <div class="mui-content">

                        <ul id="snapshotList" class="mui-table-view">
                            <!-- <li class="mui-table-view-cell mui-media">
									<a href="javascript:;" id="aaaa">
										<div id="isRead"></div>
										<img class="mui-media-object mui-pull-left" src="../css/registLogin/avatar.jpg">
										<div class="mui-media-body">
											<span>小花</span>
											<p class="mui-ellipsis">你好</p>
										</div>
									</a>
								</li>
								<li class="mui-table-view-cell mui-media">
									<a href="javascript:;">
										<img class="mui-media-object mui-pull-left" src="../css/registLogin/avatar.jpg">
										<div class="mui-media-body">
											<span>小米</span>
											<p class="mui-ellipsis">你好</p>
										</div>
									</a>
								</li> -->

                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>

</body>
<script src="../js/mui.js"></script>
<script src="../js/app.js"></script>

<script type="text/javascript">
    mui.init();
    mui.plusReady(function() {
        //添加自定义事件，刷新好友请求
        window.addEventListener("refresh", function() {
            var wobj = plus.webview.getWebviewById("wh-chatlist.html");

            wobj.reload(true);
            CHAT.init();
        });

        var user = app.getUserGlobalInfo();
        if (user != null) {
            var imgURL = user.faceImage.substring(0, 4) === "http" ? user.faceImage : app.imgServerUrl + user.faceImage;
            document.getElementById('faceImage').src = imgURL;
            document.getElementById('link_mui_action').src = imgURL;

            document.getElementById('my-meun-content').style = 'background: url(' + imgURL + ');background-size: cover;';
            document.getElementById('username').innerText = '微涵号:' + user.username;
            document.getElementById('nickname').innerText = '昵称:' + user.nickname;

            document.getElementById('link_mui_action').addEventListener('tap', function(event) {
                if (!mui('.mui-off-canvas-wrap').offCanvas().isShown()) {
                    mui('.mui-off-canvas-wrap').offCanvas().show();
                } else {
                    mui('.mui-off-canvas-wrap').offCanvas().close();
                }
            })
        }
        CHAT.init();
    })



    window.CHAT = {
        socket: null,
        init: function() {
            //判断浏览器是否支持websocket
            if (window.WebSocket) {
                //如果当前WebSocket 状态已经连接，无需重复初始化WebSocket
                if (CHAT.socket != null && CHAT.socket != undefined && CHAT.socket.readyState == WebSocket.OPEN) {
                    return false;
                }
                //创建websocket 对象
                try {
                    CHAT.socket = new WebSocket(app.nettyServerUrl);
                    CHAT.socket.onopen = CHAT.wsopen,
                        CHAT.socket.close = CHAT.wsclose,
                        CHAT.socket.onerror = CHAT.wserror,
                        CHAT.socket.onmessage = CHAT.wsmessage
                } catch (e) {
                    console.log(e.message);
                }
            } else {
                console.log("您的手机系统版本过低，请升级设备");
            }
        },
        chat: function(msg) {
            //渲染快照页面
            loadChatSnapshot();
            //将客户输入的消息推送
            CHAT.socket.send(msg);
        },
        reChat: function(msg) { //socket 重连机制
            console.log("消息重新发送");
            CHAT.socket.send(msg);
        },
        wsopen: function() {
            console.log("websocket 已连接");
            var me = app.getUserGlobalInfo();
            var meId = me.id;

            //构建聊天
            var chatMsg = new app.ChatMsg(meId, null, null, null, null);
            //构建DataContent
            var dataContent = new app.DataContent(app.CONNECT, chatMsg, null);
            CHAT.chat(JSON.stringify(dataContent));
            //查询所有未签收的消息
            queryUnSignMsg();
        },
        wsmessage: function(e) {
            var dataContent = JSON.parse(e.data);
            var chatMsg = dataContent.msg;
            var wsWebView = plus.webview.getWebviewById('wh-chat-page' + chatMsg.sendId);
            var content = chatMsg.content;
            var type = chatMsg.type;
            app.saveUserChatHistory(app.getUserGlobalInfo().id, chatMsg.sendId, content, 2, type);
            //保存快照 如果webview为空就代表未读否则已读
            var isRead = true;
            if (wsWebView != null) {
                //已读
                wsWebView.evalJS("receiveMsg('" + content + "','" + type + "');");
            } else {
                //未读
                isRead = false;
            }
            //收到消息之后 签收
            signMessage(chatMsg.msgId);

            //保存快照
            app.saveUserChatSnapshot(app.getUserGlobalInfo().id, chatMsg.sendId, content, isRead, type);
            //渲染快照页面
            loadChatSnapshot();


        },
        wsclose: function() {
            console.log("连接关闭.......");
        },
        wserror: function() {
            console.log("发生错误.....");
        },
        signMsgList: function(unSignedMsgIds) {
            //构建批量签收对象的模型
            var dataContentSign = new app.DataContent(app.SIGNED, null, unSignedMsgIds);
            //发送批量签收的请求
            CHAT.chat(JSON.stringify(dataContentSign));
        },
        keepalive: function() {
            //构建对象
            var dataConetent = new app.DataContent(app.KEEPALIVE, null, null);
            //发送心跳
            CHAT.chat(JSON.stringify(dataConetent));
            //需要定时执行的函数
            fetchUnReadMsg();
            fetchContactList(user);
        }
    };

    //签收消息
    function signMessage(msgId) {
        //初始化消息条数
        mui.ajax(app.serverUrl + '/user/signMessage', {
            data: {
                msgId: msgId
            },
            type: 'post', //HTTP请求类型
            timeout: 10000, //超时时间设置为10秒；
            success: function(data) {

            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                if (textStatus == "timeout") {
                    mui.toast("连接超时"); //超过十秒报错
                } else if (textStatus == "error") {
                    mui.toast("连接出错");
                }
            }
        });
    }

    function queryUnSignMsg() {
        //初始化消息条数
        mui.ajax(app.serverUrl + '/user/queryUnSignMsg', {
            data: {
                myId: app.getUserGlobalInfo().id
            },
            type: 'post', //HTTP请求类型
            timeout: 10000, //超时时间设置为10秒；
            success: function(data) {
                var msgList = data.data;
                if (data.status == 200) {
                    var me = app.getUserGlobalInfo();
                    for (var i = 0; i < msgList.length; i++) {
                        var msg = msgList[i];
                        //同步聊天记录
                        app.saveUserChatHistory(me.id, msg.sendUserId, msg.msg, 2, msg.type);
                        //保持快照设置未读
                        app.saveUserChatSnapshot(me.id, msg.sendUserId, msg.msg, false, msg.type);
                        //全部签收
                        signMessage(msg.id);
                    }
                    //渲染快照页面
                    loadChatSnapshot();
                }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                if (textStatus == "timeout") {
                    mui.toast("连接超时"); //超过十秒报错
                } else if (textStatus == "error") {
                    mui.toast("连接出错");
                }
            }
        });
    }

    //渲染聊天页面的函数
    function loadChatSnapshot() {
        document.getElementById('snapshotList').innerHTML = '';
        var user = app.getUserGlobalInfo();
        var chatSnapshotList = app.getUserChatSnapshot(user.id);
        if (chatSnapshotList.length > 0) {
            document.getElementById('wh-count').innerText = '微涵(' + chatSnapshotList.length + ')';
        } else {
            document.getElementById('wh-count').innerText = '微涵[暂无消息]';
        }

        var SnapshotHtml = '';
        for (var i = 0; i < chatSnapshotList.length; i++) {

            var item = chatSnapshotList[i];
            var firendId = item.friendId;
            var firend = app.getUserInfo(firendId);
            var imgURL = firend.friendFaceImage.substring(0, 4) === "http" ? firend.friendFaceImage : app.imgServerUrl +
                firend.friendFaceImage;


            var str = '';
            if (item.type == 1) {
                item.msg = '[图片]';
            }
            var isRead = '';
            if (!item.isRead) {
                isRead = '<div id="isRead"></div>';
            }
            str =
                `
					<li friendUserId="` + firendId + `" friendNickname="` + firend.friendNickname +
                `" friendFaceImage="` + firend.friendFaceImage +
                `" class="mui-table-view-cell mui-media chat-with-friend">
					<div class="mui-slider-right mui-disabled">
						<a class="mui-btn mui-btn-red link_delChatRecord" friendUserId="` +
                firendId + `">删除</a>
					</div>
						<a href="javascript:;" id="aaaa" class="mui-slider-handle">
					` + isRead +
                `
							<img class="mui-media-object mui-pull-left" src="` +
                imgURL + `">
							<div class="mui-media-body">
								<span>` +
                firend.friendNickname + `</span>
								<p class="mui-ellipsis">` + item.msg +
                `</p>
							</div>
						</a>
					</li>	
				`;
            SnapshotHtml += str;
        }

        document.getElementById('snapshotList').innerHTML = SnapshotHtml;

        mui('#snapshotList').on('tap', '.chat-with-friend', function() {
            loadChatSnapshot();
            var friendNickname = this.getAttribute("friendNickname");
            var friendFaceImage = this.getAttribute("friendFaceImage");
            var friendUserId = this.getAttribute("friendUserId");
            //更新已读消息
            app.loadUserChatSnapshot(app.getUserGlobalInfo().id, friendUserId)
                //打开聊天页面
            mui.openWindow({
                url: "wh-chat-page.html",
                id: "wh-chat-page" + friendUserId, //每个好友的聊天页面都是一一对应的
                extras: {
                    friendUserId: friendUserId,
                    friendNickname: friendNickname,
                    friendFaceImage: friendFaceImage
                }
            });

        })


        //绑定触摸事件
        mui('#snapshotList').on('tap', '.link_delChatRecord', function(e) {
            var me = this;
            //删除聊天记录
            app.deleteUserChatHistory(app.getUserGlobalInfo().id, me.getAttribute("friendUserId"));
            //删除快照
            app.deleteUserChatSnapshot(app.getUserGlobalInfo().id, me.getAttribute("friendUserId"));
            //重新渲染
            loadChatSnapshot();
        })

    }
</script>

</html>